<template>
  <div class="drone-types-container">
    <div class="page-header">
      <h2>无人机型号管理</h2>
      <el-button type="primary" @click="handleAddType" size="default">
        <el-icon><component is="i-plus" /></el-icon>
        添加型号
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <el-card class="search-card" shadow="hover">
      <el-form :model="searchForm" class="search-form">
        <el-form-item label="型号名称">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入型号名称"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item label="品牌">
          <el-input
            v-model="searchForm.brand"
            placeholder="请输入品牌"
            clearable
            size="small"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" size="small">
            <el-icon><component is="i-search" /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch" size="small">
            <el-icon><component is="i-refresh-left" /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 无人机型号表格 -->
    <el-card class="drone-types-table-card" shadow="hover">
      <el-table
        :data="droneTypesData"
        style="width: 100%"
        border
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column prop="id" label="ID" width="80" fixed />
        <el-table-column prop="name" label="型号名称" width="200">
          <template #default="{ row }">
            <el-tag size="default" effect="light">{{ row.name }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="brand" label="品牌" width="150" />
        <el-table-column
          prop="max_flight_time"
          label="最大飞行时间"
          width="120"
        >
          <template #default="{ row }">
            {{ row.max_flight_time }} 分钟
          </template>
        </el-table-column>
        <el-table-column
          prop="max_flight_distance"
          label="最大飞行距离"
          width="120"
        >
          <template #default="{ row }">
            {{ row.max_flight_distance }} km
          </template>
        </el-table-column>
        <el-table-column prop="max_speed" label="最大速度" width="100">
          <template #default="{ row }"> {{ row.max_speed }} km/h </template>
        </el-table-column>
        <el-table-column prop="weight" label="重量" width="100">
          <template #default="{ row }"> {{ row.weight }} g </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="success"
              size="small"
              @click="handleEditType(row)"
              :disabled="editingId === row.id"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteType(row)"
              :disabled="deletingId === row.id"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑无人机型号对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加无人机型号' : '编辑无人机型号'"
      width="600px"
      destroy-on-close
    >
      <el-form
        :model="droneTypeForm"
        :rules="droneTypeRules"
        ref="droneTypeFormRef"
        label-width="120px"
        class="drone-type-form"
      >
        <el-form-item label="型号名称" prop="name">
          <el-input v-model="droneTypeForm.name" placeholder="请输入型号名称" />
        </el-form-item>

        <el-form-item label="品牌" prop="brand">
          <el-input v-model="droneTypeForm.brand" placeholder="请输入品牌" />
        </el-form-item>

        <el-form-item label="最大飞行时间" prop="max_flight_time">
          <el-input-number
            v-model="droneTypeForm.max_flight_time"
            :min="1"
            :max="500"
            placeholder="请输入最大飞行时间"
            size="large"
          >
            <template #append>分钟</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="最大飞行距离" prop="max_flight_distance">
          <el-input-number
            v-model="droneTypeForm.max_flight_distance"
            :min="1"
            :max="100"
            placeholder="请输入最大飞行距离"
            size="large"
          >
            <template #append>km</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="最大速度" prop="max_speed">
          <el-input-number
            v-model="droneTypeForm.max_speed"
            :min="1"
            :max="200"
            placeholder="请输入最大速度"
            size="large"
          >
            <template #append>km/h</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="重量" prop="weight">
          <el-input-number
            v-model="droneTypeForm.weight"
            :min="1"
            :max="10000"
            placeholder="请输入重量"
            size="large"
          >
            <template #append>g</template>
          </el-input-number>
        </el-form-item>

        <el-form-item label="描述" prop="description">
          <el-input
            v-model="droneTypeForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="dialogLoading"
          >
            {{ dialogLoading ? "提交中..." : "确定" }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { droneTypeService } from '@/api';

export default {
  name: "DroneTypes",
  setup() {
    const loading = ref(false);
    const dialogVisible = ref(false);
    const dialogType = ref("add"); // 'add' or 'edit'
    const dialogLoading = ref(false);
    const droneTypeFormRef = ref(null);
    const editingId = ref(null);
    const deletingId = ref(null);

    // 搜索表单
    const searchForm = reactive({
      name: "",
      brand: "",
    });

    // 分页
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0,
    });

    // 无人机型号表单
    const droneTypeForm = reactive({
      id: "",
      name: "",
      brand: "",
      max_flight_time: 30,
      max_flight_distance: 10,
      max_speed: 60,
      weight: 1000,
      description: "",
    });

    // 表单验证规则
    const droneTypeRules = {
      name: [{ required: true, message: "请输入型号名称", trigger: "blur" }],
      brand: [{ required: true, message: "请输入品牌", trigger: "blur" }],
      max_flight_time: [
        { required: true, message: "请输入最大飞行时间", trigger: "blur" },
        {
          type: "number",
          min: 1,
          message: "最大飞行时间必须大于0",
          trigger: "blur",
        },
      ],
      max_flight_distance: [
        { required: true, message: "请输入最大飞行距离", trigger: "blur" },
        {
          type: "number",
          min: 1,
          message: "最大飞行距离必须大于0",
          trigger: "blur",
        },
      ],
    };

    // 无人机型号数据（从API获取）
    const droneTypesData = ref([]);

    // 初始化
    onMounted(() => {
      fetchDroneTypes();
    });

    // 获取无人机型号列表
    const fetchDroneTypes = async () => {
      loading.value = true;
      try {
        // 准备查询参数
        const params = {
          page: pagination.currentPage,
          page_size: pagination.pageSize,
          name: searchForm.name || undefined,
        };

        // 使用统一服务调用
        const response = await droneTypeService.getDroneTypes(params);

        // 处理响应数据
        if (response.code === 200 && response.data) {
          // 转换后端数据格式为前端需要的格式
          droneTypesData.value = response.data.items.map((type) => {
            // 尝试从description中提取品牌和重量信息
            let brand = "未知品牌";
            let weight = 0;

            // 简化处理，根据name判断品牌
            if (type.name.includes("DJI")) brand = "DJI";
            else if (type.name.includes("Autel")) brand = "Autel";
            else if (type.name.includes("Skydio")) brand = "Skydio";

            return {
              id: type.id,
              name: type.name,
              brand: brand,
              max_flight_time: type.max_flight_time || 0,
              max_flight_distance: 10, // 假设默认值
              max_speed: type.max_speed || 0,
              weight: weight || 1000, // 假设默认值
              created_at: new Date(type.created_at).toLocaleString("zh-CN"),
              description: type.description || "",
            };
          });

          // 更新分页信息
          pagination.total = response.data.total;
        } else {
          ElMessage.error("获取无人机型号列表失败");
        }
      } catch (error) {
        console.error("获取无人机型号列表失败:", error);
        ElMessage.error("获取无人机型号列表失败");
      } finally {
        loading.value = false;
      }
    };

    // 搜索
    const handleSearch = () => {
      pagination.currentPage = 1;
      fetchDroneTypes();
    };

    // 重置搜索
    const resetSearch = () => {
      Object.keys(searchForm).forEach((key) => {
        searchForm[key] = "";
      });
      pagination.currentPage = 1;
      fetchDroneTypes();
    };

    // 分页处理
    const handleSizeChange = (size) => {
      pagination.pageSize = size;
      fetchDroneTypes();
    };

    const handleCurrentChange = (current) => {
      pagination.currentPage = current;
      fetchDroneTypes();
    };

    // 打开添加无人机型号对话框
    const handleAddType = () => {
      dialogType.value = "add";
      resetDroneTypeForm();
      dialogVisible.value = true;
    };

    // 打开编辑无人机型号对话框
    const handleEditType = (row) => {
      dialogType.value = "edit";
      editingId.value = row.id;
      // 复制数据
      Object.assign(droneTypeForm, row);
      dialogVisible.value = true;
    };

    // 删除无人机型号
    const handleDeleteType = (row) => {
      ElMessageBox.confirm(`确定要删除无人机型号「${row.name}」吗？`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          deletingId.value = row.id;
          try {
            // 使用统一服务调用
            const response = await droneTypeService.deleteDroneType(row.id);

            console.log("删除响应:", response);

            if (response.code === 200) {
              ElMessage.success("删除成功");
              fetchDroneTypes();
            } else {
              throw new Error(response.detail || "删除失败");
            }
          } catch (error) {
            console.error("删除失败:", error.response.data.detail);
            // ElMessage.error(error.response.data.detail || "删除失败");
          } finally {
            deletingId.value = null;
          }
        })
        .catch(() => {
          // 取消删除
        });
    };

    // 重置无人机型号表单
    const resetDroneTypeForm = () => {
      if (droneTypeFormRef.value) {
        droneTypeFormRef.value.resetFields();
      }
      Object.assign(droneTypeForm, {
        id: "",
        name: "",
        brand: "",
        max_flight_time: 30,
        max_flight_distance: 10,
        max_speed: 60,
        weight: 1000,
        description: "",
      });
    };

    // 提交表单
    const handleSubmit = async () => {
      droneTypeFormRef.value.validate(async (valid) => {
        if (valid) {
          dialogLoading.value = true;
          try {
            // 准备请求数据
            const formData = {
              name: droneTypeForm.name,
              description: droneTypeForm.description,
              max_speed: droneTypeForm.max_speed,
              max_payload: droneTypeForm.weight / 1000, // 将重量转换为载重能力（kg）
              max_flight_time: droneTypeForm.max_flight_time,
            };

            if (dialogType.value === "add") {
              // 使用统一服务调用
              const response = await droneTypeService.createDroneType(formData);

              if (response.data.code === 200) {
                ElMessage.success("添加成功");
              } else {
                throw new Error(response.data.message || "添加失败");
              }
            } else {
              // 使用统一服务调用
              const response = await droneTypeService.updateDroneType(droneTypeForm.id, formData);

              if (response.data.code === 200) {
                ElMessage.success("更新成功");
              } else {
                throw new Error(response.data.message || "更新失败");
              }
            }

            dialogVisible.value = false;
            fetchDroneTypes();
            editingId.value = null;
          } catch (error) {
            console.error("操作失败:", error);
            ElMessage.error(error.message || "操作失败");
          } finally {
            dialogLoading.value = false;
          }
        }
      });
    };

    return {
      loading,
      dialogVisible,
      dialogType,
      dialogLoading,
      droneTypeFormRef,
      searchForm,
      pagination,
      droneTypeForm,
      droneTypeRules,
      droneTypesData,
      editingId,
      deletingId,
      handleSearch,
      resetSearch,
      handleSizeChange,
      handleCurrentChange,
      handleAddType,
      handleEditType,
      handleDeleteType,
      handleSubmit,
    };
  },
};
</script>

<style scoped>
.drone-types-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: end;
}

.search-form .el-form-item {
  margin-bottom: 15px;
}

.drone-types-table-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.drone-type-form .el-form-item {
  margin-bottom: 20px;
}
</style>
